﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using CodeCamp12.BLL;
namespace CodeCamp12
{
    /// <summary>
    /// Summary description for GetFileForSpeaker
    /// </summary>
    public class GetFileForSpeaker : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            var response = HttpContext.Current.Response;
            var speakerId = HttpContext.Current.Request.QueryString["id"];
            
            var speakerBuissProvider = new SpeakersBL();
            try
            {
                if(String.IsNullOrEmpty(speakerId))
                {
                    throw new Exception("In GetFileForSpeaker.ashx : ProcessRequest - query string parametar speakerId can not be null or empty");
                }
                else
                {
                    var file = speakerBuissProvider.GetFileForSpeaker(new Guid(speakerId));
                    if (file.FileType.Equals(".pdf"))
                        response.ContentType = "application/pdf";
                    else
                        response.ContentType = "application/vnd.ms-word";

                    var fileStream = file.FileData;
                    var reader = new BinaryReader(fileStream);
                    response.AddHeader("Content-Disposition", "attachment; filename=" + file.FileName);
                    response.ClearContent();
                    response.OutputStream.Write(reader.ReadBytes(Convert.ToInt32(fileStream.Length)), 0, Convert.ToInt32(fileStream.Length));
                    response.End();
                }
                
            }
            catch (Exception)
            {   
                throw;
            }
            
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }


        
    }
}
